package com.telecom.sxint.app.core.service.impl.Engineerserviceimpl;

import cn.hutool.core.collection.CollUtil;
import cn.zjtele.pubinfo.boot.redis.config.RedisHelper;
import cn.zjtele.pubinfo.common.http.response.ResponseData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.telecom.sxint.app.core.domain.entity.Engineerpojo.App1Engineercertification;
import com.telecom.sxint.app.core.domain.entity.Query.PageData;
import com.telecom.sxint.app.core.domain.entity.dto.CertificationQueryDTO;
import com.telecom.sxint.app.core.mapper.Engineermapper.App1EngineercertificationMapper;
import com.telecom.sxint.app.core.service.Engineerservice.IApp1EngineercertificationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2024-08-19
 */
@CacheConfig(cacheNames = "app1Engineercertification")
@Service
public class App1EngineercertificationServiceImpl extends ServiceImpl<App1EngineercertificationMapper, App1Engineercertification> implements IApp1EngineercertificationService {
    @Autowired
    private  App1EngineercertificationMapper app1EngineercertificationMapper;
    @Autowired
    private RedisHelper redisHelper;
    private Integer changes(String engineerLevel) {
        if (!engineerLevel.isEmpty()){
            char lastChar = engineerLevel.charAt(engineerLevel.length() - 1); // 获取最后一个字符
            int lastCharAsInt = Character.getNumericValue(lastChar);
            return lastCharAsInt;
        }
        return 0;
    }
    /**
     * 修改明细
     * @param app1Engineercertification
     * @return
     */
    @Override
    public App1Engineercertification updateByIdrdate(App1Engineercertification app1Engineercertification) {
        String cacheKey="engineer_certification:"+app1Engineercertification.getId();
        App1Engineercertification cachedData=(App1Engineercertification)redisHelper.valueGet(cacheKey);
        if (cachedData!=null){
            redisHelper.delete(cacheKey);
        }
        //修改前获取三个级别数据
        String rdCommonLevel = app1Engineercertification.getRdCommonLevel();
        String rdProfessionLevel = app1Engineercertification.getRdProfessionLevel();
        String rdExperienceLevel = app1Engineercertification.getRdExperienceLevel();

        QueryWrapper<App1Engineercertification> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("personnel_code",app1Engineercertification.getPersonnelCode());
        App1Engineercertification log1=app1EngineercertificationMapper.selectOne(queryWrapper1);
        List<Integer> minNum=new ArrayList<>();
        //如果这三部分没修改或者只修改部分则根据id查询数据库获取修改部分的数据，根据字符串最后一个字符转换成int类型添加进数组
        if (rdCommonLevel==null ||rdCommonLevel.isEmpty()){
            rdCommonLevel=log1.getRdCommonLevel();
            minNum.add(changes(rdCommonLevel));
        }
        else {
            minNum.add(changes(rdCommonLevel));
        }
        if (rdProfessionLevel==null||rdProfessionLevel.isEmpty()){
            rdProfessionLevel=log1.getRdProfessionLevel();
            minNum.add(changes(rdProfessionLevel));
        }
        else {
            minNum.add(changes(rdProfessionLevel));
        }
        if(rdExperienceLevel==null||rdExperienceLevel.isEmpty() ){
            rdExperienceLevel=log1.getRdExperienceLevel();
            minNum.add(changes(rdExperienceLevel));
        }
        else {
            minNum.add(changes(rdExperienceLevel));
        }

        //最小值为代表三个等级中有空
        if (Collections.min(minNum)==0) {
            app1Engineercertification.setEngineerLevel("");
        }
        //其余level设为空
        else {
            app1Engineercertification.setEngineerLevel("研发工程师L"+ Collections.min(minNum));
        }
        UpdateWrapper<App1Engineercertification> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("personnel_code", app1Engineercertification.getPersonnelCode());
        app1EngineercertificationMapper.update(app1Engineercertification,updateWrapper);
        QueryWrapper<App1Engineercertification> queryWrapper2=new QueryWrapper<>();
        queryWrapper2.eq("personnel_code",app1Engineercertification.getPersonnelCode());
        App1Engineercertification log2=app1EngineercertificationMapper.selectOne(queryWrapper2);
        redisHelper.valueSet(cacheKey,log2,3600L, TimeUnit.SECONDS);

        return log2;
    }

    /**
     * 根据条件查询工程师数据
     * @param filter
     * @return
     */
    @Override
    public List<App1Engineercertification> queryByConditions(App1Engineercertification filter) {
        QueryWrapper<App1Engineercertification> queryWrapper = new QueryWrapper<>();
        // 确保只查询is_delete为0的记录
        queryWrapper.eq("is_delete", 0);
        if (filter.getCompany() != null && !filter.getCompany().isEmpty()) {
            queryWrapper.eq("company", filter.getCompany());
        }
        if (filter.getPersonnelCode() != null && !filter.getPersonnelCode().isEmpty()) {
            queryWrapper.eq("personnel_code", filter.getPersonnelCode());
        }
        if (filter.getName() != null && !filter.getName().isEmpty()) {
            queryWrapper.eq("name", filter.getName());
        }
        if (filter.getIsRdCloud() != null) {
            queryWrapper.eq("is_rd_cloud", filter.getIsRdCloud());
        }
        if (filter.getIsRdBase() != null) {
            queryWrapper.eq("is_rd_base", filter.getIsRdBase());
        }
        if (filter.getIsRdCommon() != null) {
            queryWrapper.eq("is_rd_common", filter.getIsRdCommon());
        }
        if (filter.getRdCommonLevel() != null && !filter.getRdCommonLevel().isEmpty()) {
            queryWrapper.eq("rd_common_level", filter.getRdCommonLevel());
        }
        if (filter.getIsRdProfession() != null) {
            queryWrapper.eq("is_rd_profession", filter.getIsRdProfession());
        }
        if (filter.getRdProfessionLevel() != null && !filter.getRdProfessionLevel().isEmpty()) {
            queryWrapper.eq("rd_profession_level", filter.getRdProfessionLevel());
        }
        if (filter.getRdExperienceLevel() != null && !filter.getRdExperienceLevel().isEmpty()) {
            queryWrapper.eq("rd_experience_level", filter.getRdExperienceLevel());
        }
        if (filter.getEngineerLevel() != null && !filter.getEngineerLevel().isEmpty()) {
            queryWrapper.eq("engineer_level", filter.getEngineerLevel());
        }

        return app1EngineercertificationMapper.selectList(queryWrapper);
    }

    /**
     * 明细表分页查询
     * @param certificationQueryDTO
     * @return
     */
    @Override
    public PageData queryCertificationPage(CertificationQueryDTO certificationQueryDTO) {
        //1构建查询条件
        Page<App1Engineercertification> page = Page.of(certificationQueryDTO.getCurrentPage(), certificationQueryDTO.getPageSize());
        //排序  page.addOrder(new OrderItem(ticketQueryDTO.))
        //2分页查询
        Page<App1Engineercertification> p = lambdaQuery()
                .eq(App1Engineercertification::getIsDelete, 0) // 确保只查询is_delete为0的记录
                .page(page);
        //3封装VO结果
        PageData<App1Engineercertification> dto = new PageData<>();
        //总条数
        dto.setTotal(p.getTotal());
        //当前页
        dto.setCurrentPage(p.getCurrent());
        dto.setPageSize(p.getSize());
        //当前页数条数
        //当前页数据
        List<App1Engineercertification> records = p.getRecords();
        dto.setRecords(records);
        //4返回
        return dto;
    }

    /**
     *获取研发人员各等级区县分布
     * @param level
     * @return
     */
    @Override
    public List<Map<String, Object>> getCompanyCountByLevel(Integer level) {
        String cacheKey="engineer_certification_company_count_by_level:"+level;
        List<Map<String, Object>> cachedData=(List<Map<String, Object>>)redisHelper.valueGet(cacheKey);
        if (cachedData!=null){
            return cachedData;
        }
        QueryWrapper<App1Engineercertification> wrapper =new QueryWrapper<>();
        wrapper.select(" company , count(*) as total")
                .eq("is_delete", 0)// 添加条件，确保只查询 is_delete 字段为 0 的记录
                .eq("engineer_level","研发工程师L"+level)
                .groupBy("company");

        List<Map<String, Object>> list = app1EngineercertificationMapper.selectMaps(wrapper);
        redisHelper.valueSet(cacheKey,list,3600L, TimeUnit.SECONDS);
        return list;
    }

    /**
     *获取研发人员认证级别缺失情况
     * @return
     */
    @Override
    @Transactional
    public List<Map<String, Object>> getLostSituation() {
        String cacheKey="engineer_certification_lost_situation";
        List<Map<String, Object>> cachedData=(List<Map<String, Object>>)redisHelper.valueGet(cacheKey);
        if (cachedData!=null){
            return cachedData;
        }
        app1EngineercertificationMapper.updatenull1();
        QueryWrapper<App1Engineercertification> wrapper =new QueryWrapper<>();
        wrapper.select("count(*) as total,count(rd_common_level) as rd_common_level_num,count(rd_profession_level) as rd_profession_level_num,count(rd_experience_level) as rd_experience_level_num")
                .eq("is_delete", 0);
        List<Map<String,Object>> list = app1EngineercertificationMapper.selectMaps(wrapper);
        app1EngineercertificationMapper.updatenull2();
        redisHelper.valueSet(cacheKey,list,3600L, TimeUnit.SECONDS);
        return list;
    }

    /*
     *查询所有工程师数据
     */
    @Override
    public List<App1Engineercertification> queryAllCertification() {
        String cacheKey="engineer_certification_all";
        List<App1Engineercertification> cachedData=(List<App1Engineercertification>)redisHelper.valueGet(cacheKey);
        if (cachedData!=null){
            return cachedData;
        }
        QueryWrapper<App1Engineercertification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0); // 确保只查询is_delete为0的记录
        List<App1Engineercertification> list = app1EngineercertificationMapper.selectList(queryWrapper);
        redisHelper.valueSet(cacheKey,list,3600L, TimeUnit.SECONDS);
        return list;
    }
    /**
     * 批量删除研究人员信息
     * @param ids
     * @return
     */
    @Override
    public void deletByIds(List<Integer> ids) {
        redisHelper.deletePattern("engineer_certification*");
        if (CollUtil.isEmpty(ids)) {
            return;
        }
        UpdateWrapper<App1Engineercertification> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", ids) // 设置更新条件，这里假设id是更新条件
                .set("is_delete", 1); // 设置 is_delete 字段的值为 1
        // 调用服务类的 update 方法进行批量更新
        app1EngineercertificationMapper.update(null, updateWrapper);
    }

    @Override
    public PageData queryByCompanyPage(CertificationQueryDTO certificationQueryDTO, String company) {
        Page<App1Engineercertification> page = Page.of(certificationQueryDTO.getCurrentPage(), certificationQueryDTO.getPageSize());
        //排序  page.addOrder(new OrderItem(ticketQueryDTO.))
        //2分页查询
        Page<App1Engineercertification> p = lambdaQuery()
                .eq(App1Engineercertification::getCompany, company)
                .eq(App1Engineercertification::getIsDelete, 0) // 确保只查询is_delete为0的记录
                .page(page);
        //3封装VO结果
        PageData<App1Engineercertification> dto = new PageData<>();
        //总条数
        dto.setTotal(p.getTotal());
        //当前页
        dto.setCurrentPage(p.getCurrent());
        dto.setPageSize(p.getSize());
        //当前页数条数
        //当前页数据
        List<App1Engineercertification> records = p.getRecords();
        dto.setRecords(records);
        //4返回
        return dto;
    }
    /**
     * 根据ID查询工程师数据
     * @param id
     * @return
     */
    @Override
    public App1Engineercertification queryById(Integer id) {
        String cacheKey="engineer_certification:"+id;
        App1Engineercertification cachedData=(App1Engineercertification)redisHelper.valueGet(cacheKey);
        if (cachedData!=null){
            return cachedData;
        }
        QueryWrapper<App1Engineercertification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.eq("is_delete", 0); // 确保只查询is_delete为0的记录
        App1Engineercertification log = app1EngineercertificationMapper.selectOne(queryWrapper);
        redisHelper.valueSet(cacheKey,log,3600L, TimeUnit.SECONDS);
        return log;
    }
    /**
     * 新增明细
     * @param app1Engineercertification
     * @return
     */
    @Override
    public ResponseData addCertification(App1Engineercertification app1Engineercertification) {
        if(app1Engineercertification.getPersonnelCode()==null||app1Engineercertification.getPersonnelCode().isEmpty()){
            return ResponseData.failed("人员编码不能为空",null);
        }else if(app1Engineercertification.getName()==null||app1Engineercertification.getName().isEmpty()){
            return ResponseData.failed("姓名不能为空",null);
        }else if(app1Engineercertification.getCompany()==null||app1Engineercertification.getCompany().isEmpty()){
            return ResponseData.failed("公司不能为空",null);
        }   else if(app1Engineercertification.getIsRdCloud()==null){
            return ResponseData.failed("是否云研发不能为空",null);
        }else if(app1Engineercertification.getIsRdBase()==null){
            return ResponseData.failed("是否基础研发不能为空",null);
        }else if(app1Engineercertification.getIsRdCommon()==null){
            return ResponseData.failed("是否通用研发不能为空",null);
        }
        // 检查数据库中是否已存在相同的人员编码
        QueryWrapper<App1Engineercertification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("personnel_code", app1Engineercertification.getPersonnelCode())
                .eq("is_delete",0);
        App1Engineercertification existingRecord = app1EngineercertificationMapper.selectOne(queryWrapper);
        if (existingRecord != null) {
            return ResponseData.failed("该人员编码已存在，不能重复添加", null);
        }

        redisHelper.deletePattern("engineer_certification*");
        String cacheKey="engineer_certification:"+app1Engineercertification.getId();
        App1Engineercertification cachedData=(App1Engineercertification)redisHelper.valueGet(cacheKey);
        if (cachedData!=null){
            redisHelper.delete(cacheKey);
        }
        //新增时获取三个级别数据
        String rdCommonLevel = app1Engineercertification.getRdCommonLevel();
        String rdProfessionLevel = app1Engineercertification.getRdProfessionLevel();
        String rdExperienceLevel = app1Engineercertification.getRdExperienceLevel();
        List<Integer> minNum=new ArrayList<>();
        //如果这三部分没修改或者只修改部分则根据id查询数据库获取修改部分的数据，根据字符串最后一个字符转换成int类型添加进数组
        if (rdCommonLevel==null ||rdCommonLevel.isEmpty()){
            minNum.add(changes(rdCommonLevel));
        }
        else {
            minNum.add(changes(rdCommonLevel));
        }
        if (rdProfessionLevel==null||rdProfessionLevel.isEmpty()){
            minNum.add(changes(rdProfessionLevel));
        }
        else {
            minNum.add(changes(rdProfessionLevel));
        }
        if(rdExperienceLevel==null||rdExperienceLevel.isEmpty() ){
            minNum.add(changes(rdExperienceLevel));
        }
        else {
            minNum.add(changes(rdExperienceLevel));
        }
        //最小值为代表三个等级中有空
        if (Collections.min(minNum)==0) {
            app1Engineercertification.setEngineerLevel("");
        }
        //其余level设为空
        else {
            app1Engineercertification.setEngineerLevel("研发工程师L"+ Collections.min(minNum));
        }
        app1Engineercertification.setId(null);
        app1Engineercertification.setIsDelete(0);
        app1EngineercertificationMapper.insert(app1Engineercertification);
        QueryWrapper<App1Engineercertification> queryWrapper2=new QueryWrapper<>();
        queryWrapper2.eq("personnel_code",app1Engineercertification.getPersonnelCode())
                .eq("is_delete",0);
        App1Engineercertification log2=app1EngineercertificationMapper.selectOne(queryWrapper2);
        redisHelper.valueSet(cacheKey,log2,3600L, TimeUnit.SECONDS);
        return ResponseData.success(log2);
    }
}
